#include "UserManager.h"
#include "LeagueManager.h"
#include "Team.h"
#include "Utilities.h"
#include "League.h"

#include <algorithm>

UserManager::UserManager(ServiceProvider* const i_sp)
:m_sp(i_sp)
{
}

UserManager::~UserManager()
{
	Clear();
}

void UserManager::Clear()
{
	Utilities::DeepClear(m_list);
}

void UserManager::CheckLosingPlayers()
{
	assert(!m_sp->GetLeagueMgr().GetAllLayers().empty());
	
	LeagueLayer* ghostLayer = m_sp->GetLeagueMgr().GetAllLayers().back();
	m_gameoverNames.clear();
	for(LeagueVec::iterator leagueIt = ghostLayer->GetAllLeagues().begin(); leagueIt != ghostLayer->GetAllLeagues().end(); ++leagueIt)
	{
		League* league = *leagueIt;
		for (TeamVecCit teamsIt = league->GetTeams().begin(); teamsIt != league->GetTeams().end(); ++teamsIt)
		{
			Team* team = *teamsIt;

			if (team->IsUserControlled())
			{
				// TODO Game Over!

				UsersIterator deadPlayer = std::find_if(m_list.begin(), m_list.end(), CompareUserTeamPtr(team));
				if(deadPlayer != m_list.end())
				{
					m_gameoverNames.push_back((*deadPlayer)->m_name);
//					events <<  " ! " << (*deadPlayer)->m_name  << " GAME OVER!!!\n";
					team->SetUserControlled(false);
					delete *deadPlayer;
					m_list.erase(deadPlayer);
				}
			}
		}

	}
	
}